<!-- 闯关活动 -->
<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-title filter-item">活动状态</span>
      <k-select
        v-model="listQuery.activeState"
        class="filter-item user-status"
        type="1"
        :select-params="[{ label: '未开始', value: 1 }, { label: '进行中', value: 2 }, { label: '已结束', value: 0 }]"
        @handleSelectEvent="handleFilter"
      />
      <span class="filter-title filter-item">活动时间</span>
      <k-date-picker v-model="timeValue" class="filter-item" @hqchang="handleFilter" />
      <k-input
        v-model.trim="listQuery.activityTheme"
        class="filter-item"
        is-search
        placeholder="请输入关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>

    <!-- 添加活动 -->
    <k-button v-if="authorityHandle(234)" class="top-btn" value="添加活动" @click.native="creatActivityDialog" />
    <!-- <k-button class="top-btn" value="玩法介绍" @click.native="ruleGuideDialog" /> -->

    <k-button class="top-btn" value="设置" @click.native="setPlaying" />
    <k-button class="top-btn" value="排行榜玩法介绍" @click.native="rankingDialog" />

    <!--表格相关 -->
    <el-table
      ref="dragTable"
      :data="bloodTableData"
      fit
      border
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
    >
      <el-table-column width="80px" type="index" label="序号" align="center" />
      <el-table-column prop="activityTheme" min-width="100px" label="活动主题" align="center" show-overflow-tooltip />
      <el-table-column prop="activityDescription" min-width="100px" label="活动说明" align="center" show-overflow-tooltip />
      <el-table-column min-width="150px" label="活动时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.activityTimeStart }} - {{ scope.row.activityTimeEnd }}
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="活动状态" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.activeState | stateFilter }}
        </template>
      </el-table-column>
      <el-table-column min-width="80px" label="开关" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.activeSwitch"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="0"
            :inactive-value="1"
            :disabled="!authorityHandle(234)"
            @change="updateActStatus($event, scope)"
          />
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button
              v-if="authorityHandle(234)"
              class="table-btn"
              value="查看/修改"
              @click.native="updateActivityDialog(scope.row)"
            />
            <k-button class="table-btn" value="关卡管理" @click.native="toLevel(scope.row.id)" />
            <k-button class="table-btn" value="排行榜管理" @click.native="RankingList(scope.row.id)" />
            <k-button
              v-if="authorityHandle(234)"
              class="table-btn"
              value="删除"
              @click.native="deleteActivityItem(scope.row.id)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />

    <!-- 活动弹框 -->
    <k-dialog
      :show-hide.sync="creatActivity.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(234)"
      :close-fun="handleCloseDialog"
      @click="saveActivity"
    >
      <div class="dialog_creatRollRoom">
        <el-form :model="activityInfo" label-width="auto">
          <el-form-item label="活动主题：">
            <el-input
              v-model="activityInfo.activityTheme"
              :readonly="!authorityHandle(234)"
              show-word-limit
              placeholder="请输入活动主题"
            />
          </el-form-item>

          <el-form-item label="活动说明：">
            <el-input
              v-model="activityInfo.activityDescription"
              :readonly="!authorityHandle(234)"
              type="textarea"
              :rows="5"
              placeholder="请输入活动说明"
            />
          </el-form-item>

          <el-form-item label="活动时间：" style="width:300px">
            <el-date-picker
              v-model="timeCotinue"
              :disabled="!authorityHandle(234)"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

    <!-- 玩法介绍 弹窗 -->
    <k-dialog
      :show-hide.sync="ruleGuide.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="玩法介绍"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(234)"
      :close-fun="guideClose"
      @click="guideSave"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="ruleGuideContent" label-width="auto">
          <el-form-item label="内容介绍：" prop="content">
            <quill-editor
              ref="myQuillEditor"
              v-model.trim="ruleGuideContent.content"
              :options="editorOption"
              class="editer"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

    <!-- 玩法设置 弹窗 -->
    <k-dialog
      :show-hide.sync="PlayMethodSettings"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="设置门槛"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="true"
      :close-fun="szClose"
      @click="setSave"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="setThresholdform" label-width="auto">
          <el-form-item label="闯关门槛：">
            <el-input
              v-model.number="setThresholdform.threshold"
              onkeyup="value = value.replace(/[^0-9.]/g,'')"
              show-word-limit
              placeholder="请输入闯关门槛"
            />
          </el-form-item>
          <el-form-item label="生效时间：" style="width:300px">
            <el-date-picker
              v-model="cotinueTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
    <!-- 排行榜玩法介绍 弹窗 -->
    <k-dialog
      :show-hide.sync="paihang.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="排行榜玩法介绍"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(234)"
      :close-fun="guideClose"
      @click="guideSavePaihang"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="paihang" label-width="auto">
          <el-form-item label="内容介绍：" prop="content">
            <quill-editor ref="myQuillEditor" v-model.trim="paihang.content" :options="editorOption" class="editer" />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import { saveActivity, setToConfirmRankingDescribe, getToConfirmRankingDescribe, listData, updateActivity, getThreshold, setThreshold, deleteActivity, getToConfirmDescribe, setToConfirmDescribe, SetSort } from '@/api/levelActivity/index.js'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
export default {
  components: {
    Pagination
  },

  filters: {
    stateFilter(v) {
      if (v == 0) {
        return '已结束'
      } else if (v == 1) {
        return '未开始'
      } else if (v == 2) {
        return '进行中'
      }
    }
  },
  data() {
    return {
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        activeState: '', // 根据状态查询
        activityTheme: '', // 活动主题
        activityTimeStart: undefined,
        activityTimeEnd: undefined
      },
      editorOption: {
        placeholder: '请输入内容',
        modules: {
          // 富文本初始化
          'emoji-toolbar': true,
          'emoji-shortname': true,
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            [{ script: 'sub' }, { script: 'super' }], // 上下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], // 字体
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image'], // 上传图片、上传视频
            ['emoji']
          ],
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        }
      },

      timeValue: '',

      // listData
      bloodTableData: [],
      totalRows: 0, // 分页组件--数据总条数

      // 活动item相关
      textMap: '添加活动',

      creatActivity: {
        showHide: false
      },
      activityInfo: {
        activityTheme: '',
        activityDescription: '',
        activityTimeStart: '',
        activityTimeEnd: ''
      },
      timeCotinue: '',
      // 生效时间
      cotinueTime: '',
      ruleGuide: {
        showHide: false
      },
      // 排行榜
      paihang: {
        showHide: false,
        content: ''
      },
      ruleGuideContent: {
        content: ''
      },
      // 设置
      PlayMethodSettings: false,
      setThresholdform: {
        threshold: 0,
        startTime: '',
        endTime: ''
      }
    }
  },

  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.activityTimeStart = this.timeValue ? this.timeValue[0] : null
      this.listQuery.activityTimeEnd = this.timeValue ? this.timeValue[1] : null
    },

    timeCotinue(val) {
      this.activityInfo.activityTimeStart = this.timeCotinue ? this.timeCotinue[0] : null
      this.activityInfo.activityTimeEnd = this.timeCotinue ? this.timeCotinue[1] : null
    },

    cotinueTime(val) {
      this.setThresholdform.startTime = this.cotinueTime ? this.cotinueTime[0] : null
      this.setThresholdform.endTime = this.cotinueTime ? this.cotinueTime[1] : null
    }
  },

  created() {
    this.loadData()
    if (this.authorityHandle(234)) {
      this.$nextTick(() => {
        this.setSort()
      })
    }
  },

  methods: {
    // 玩法介绍
    ruleGuideDialog() {
      getToConfirmDescribe().then(res => {
        this.ruleGuideContent.content = res.data
        this.ruleGuide.showHide = true
      })
    },
    // 排行榜说明
    rankingDialog() {
      getToConfirmRankingDescribe().then(res => {
        this.paihang.content = res.data
        this.paihang.showHide = true
      })
    },
    setPlaying() {
      getThreshold().then((result) => {
        const { data } = result
        this.setThresholdform = data !== null ? data : this.setThresholdform
        this.cotinueTime = data !== null ? [data.startTime === null ? '' : data.startTime, data.endTime === null ? '' : data.endTime] : ''
        this.PlayMethodSettings = true
      })
    },
    // 关闭门槛
    szClose() {
      this.PlayMethodSettings = false
    },
    // 保存设置
    async setSave() {
      try {
        await setThreshold(this.setThresholdform)
        this.$message.success('操作成功')
        this.szClose()
      } catch (e) {
        console.error('e: ', e)
      }
    },

    // 关闭玩法管理
    guideClose() {
      this.ruleGuide.showHide = false
      this.paihang.showHide = false
    },

    // 保存玩法管理
    guideSave() {
      const contents = this.ruleGuideContent.content
      setToConfirmDescribe({ 'data': contents }).then(res => {
        this.ruleGuide.showHide = false
      })
    },
    // 保存玩法管理
    guideSavePaihang() {
      const contents = this.paihang.content
      setToConfirmRankingDescribe({ 'data': contents }).then(res => {
        this.paihang.showHide = false
      })
    },

    loadData() {
      listData(this.listQuery).then(res => {
        this.totalRows = res.data.totalRows
        this.bloodTableData = res.data.rows
      })
    },

    // 排序
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const list = JSON.parse(JSON.stringify(this.bloodTableData))
          const targetRow = list.splice(evt.oldIndex, 1)[0]
          list.splice(evt.newIndex, 0, targetRow)
          list.reverse().map((item, index) => {
            item.sort = index
          })
          SetSort(list).then(res => {
            if (res.data.success) {
              this.$message.success(res.data.msg)
              this.bloodTableData = []
              this.loadData()
            }
          })
        }
      })
    },

    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.loadData()
    },

    // 排行榜管理
    RankingList(id) {
      this.$router.push({
        path: '/Ranking-management',
        query: { id }
      })
    },

    // 添加活动
    creatActivityDialog() {
      this.$resetForm(this.activityInfo)
      this.timeCotinue = ''
      this.textMap = '添加活动'
      this.creatActivity.showHide = true
    },

    // 活动开关
    updateActStatus(event, scope) {
      updateActivity({
        id: scope.row.id,
        activeSwitch: event
      }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
          this.loadData()
        } else {
          this.$message.error(res.data.msg)
          this.loadData()
        }
      })
    },

    // 更新活动
    updateActivityDialog(row) {
      this.activityInfo = JSON.parse(JSON.stringify(row))
      this.timeCotinue = [row.activityTimeStart === null ? '' : row.activityTimeStart, row.activityTimeEnd === null ? '' : row.activityTimeEnd]
      this.textMap = '修改活动'
      this.creatActivity.showHide = true
    },

    // 关卡管理
    toLevel(id) {
      this.$router.push({
        path: '/rush-level-manager',
        query: { id }
      })
    },

    // 删除活动
    deleteActivityItem(id) {
      this.$confirm('确定删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteActivity({
            id
          }).then(res => {
            if (res.data.success) {
              this.$message.success('删除成功')
              this.loadData()
            } else {
              this.$message.error(res.data.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    // 关闭弹框
    handleCloseDialog() {
      this.creatActivity.showHide = false
    },
    // 保存活动
    saveActivity() {
      if (!this.activityInfo.activityTheme || !this.activityInfo.activityDescription || !this.activityInfo.activityTimeStart || !this.activityInfo.activityTimeEnd) {
        this.$message.error('所有项必填')
        return
      }

      if (this.textMap == '添加活动') {
        saveActivity(this.activityInfo).then(res => {
          if (res.data.success) {
            this.loadData()
            this.$message.success('操作成功')
            this.creatActivity.showHide = false
          } else {
            this.$message.error(res.data.msg)
          }
        })
      } else {
        updateActivity(this.activityInfo).then(res => {
          if (res.data.success) {
            this.loadData()
            this.$message.success('操作成功')
            this.creatActivity.showHide = false
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.editer {
  border-radius: 8px;
  float: left;
  box-sizing: border-box;
  color: #606266;

  ::v-deep .ql-container {
    height: 440px;
    border-radius: 0px 0px 8px 8px;
  }

  ::v-deep .ql-toolbar.ql-snow {
    border-radius: 8px 8px 0px 0px;
  }
}

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162e;
  }

  .user-item {
    margin-left: 10px;
    margin-right: 20px;
  }

  .room-type,
  .user-status,
  .account-status {
    margin-right: 20px;
  }
}

.dialog_creatRollRoom {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 40px 80px;
  width: 500px;

  .el-form {
    width: 100%;
  }

  ::v-deep .el-select .el-select__tags>span {
    display: none;
  }

  ::v-deep .el-range-editor.el-input__inner {
    width: 400px;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;

    ::v-deep .el-tag__close {
      color: $mainColor;
    }

    ::v-deep .el-icon-close:hover {
      color: #ffffff;
      background: $mainColor;
    }
  }
}

.top-btn {
  margin: 30px 0px 30px 0px;
  font-size: 14px;
  color: #ffffff;

  &:nth-of-type(2),
  &:nth-of-type(3),
  &:nth-of-type(4) {
    margin-left: 10px;
  }
}
</style>
